<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from "vue";
import { storeToRefs } from "pinia";
import { useTradeStore } from "@/store/modules/tradeStore";
import PositionAnalysis from "@/components/tables/account/PositionAnalysis.vue";

defineOptions({
  name: "trade-position-analysis-table"
});

const props = withDefaults(
  defineProps<{
    title?: string;
    compact?: boolean;
    height?: string | null;
  }>(),
  {
    title: undefined,
    compact: false,
    height: null
  }
);

const tradeStore = useTradeStore();
const { accountInfo } = storeToRefs(tradeStore);

const positions = computed(() =>
  accountInfo.value ? Array.from(accountInfo.value.positions.values()) : []
);

const tableContainerRef = ref<HTMLElement | null>(null);
const tableHeight = ref<string | null>();

// Use provided height or calculate it
const effectiveHeight = computed(() => props.height || tableHeight.value);

const updateTableHeight = () => {
  if (!props.height && tableContainerRef.value) {
    tableHeight.value = `${tableContainerRef.value.clientHeight}px`;
  }
};

onMounted(() => {
  if (!props.height) {
    updateTableHeight();
    window.addEventListener("resize", updateTableHeight);
  }
});

onUnmounted(() => {
  if (!props.height) {
    window.removeEventListener("resize", updateTableHeight);
  }
});
</script>

<template>
  <div ref="tableContainerRef" class="h-full w-full overflow-hidden">
    <PositionAnalysis
      :position="positions"
      :height="effectiveHeight"
      :title="props.title"
      :compact="props.compact"
      size="small"
    />
  </div>
</template>
